<?php

namespace Helpers;

use Phalcon\Di;

class BaseApi
{

    /**
     * @var \Phalcon\Http\Request
     */
    public $request;

    /**
     * @var \Phalcon\Http\Response
     */
    public $response;

    /**
     * @var \Phalcon\Mvc\Dispatcher
     */
    public $dispatcher;

    /**
     * 初始化服务
     */
    public function __construct()
    {
        $di = Di::getDefault();
        $this->request = $di->get('request');
        $this->response = $di->get('response');
        $this->dispatcher = $di->get('dispatcher');
    }

    /**
     * 创建日志，自动获取项目/模块/方法名称
     *
     * @param $msg
     * @param string $detail
     * @return bool
     *
     * create by ck 20181115
     */
    private function createLog($msg, $detail = '')
    {
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2];
        return Main::createCommitLog(
            $this->dispatcher->getModuleName(),
            @end(explode('\\', $backtrace['class'])),
            $backtrace['function'],
            [
                'post' => $this->request->getPost(),
                'get' => $this->request->getQuery(),
                'body' => $this->request->getRawBody(),
                'detail' => $detail
            ],
            null,
            $msg
        );
    }

    public function returnJson($data = null, $log = false)
    {
        $log and $this->createLog('json返回成功', $data);
        return $this->response->setJsonContent($data, JSON_UNESCAPED_UNICODE);
    }

    public function returnSuccess($msg = '', $log = true, $code = 200)
    {
        $log and $this->createLog($msg);
        return $this->response->setJsonContent(
            ['code' => $code ?: 200, 'msg' => $msg ?: '成功！'],
            JSON_UNESCAPED_UNICODE
        );
    }

    public function returnError($code = 200, $error = '未知错误', $msg = '', $log = true)
    {
        $content = ['error' => $error, 'code' => $code, 'msg' => $msg];
        $log and $this->createLog($error, $msg);
        return $this->response->setStatusCode($code)->setJsonContent($content, JSON_UNESCAPED_UNICODE);
    }
}